package com.作业.Day19;


/**
 *  设计一个多线程的程序如下：设计一个火车售票模拟程序。假如火车站要有100张火车票要卖出，
 *  现在有5个售票点同时售票，用5个线程模拟这5个售票点的售票情况。
 *

 */
public class Test1 {
    public static void main(String[] args) {
        SellTicketTask sellTicketTask = new SellTicketTask();
        Thread threadA = new Thread(sellTicketTask,"检票A");
        Thread threadB = new Thread(sellTicketTask,"检票B");
        Thread threadC = new Thread(sellTicketTask,"检票C");
        Thread threadD = new Thread(sellTicketTask,"检票D");
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
    }
}
/**
 * 创建卖票的任务
 */
class SellTicketTask implements Runnable {
     private int ticketCount = 100;

    /**
     * 为什么要加锁呢？
     * 加锁是因为防止判断完没来的及减票，就断了，防止超卖
     */
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                {
                    if (ticketCount > 0) {
                        System.out.println("检票点" + Thread.currentThread().getName() + "正在出售第" + (101 - ticketCount) + "张票");
                        ticketCount--;
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }
}
